import os
import random

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time

from video_jian import add_video_cover

"""
自动发布抖音和快手2.0版本
author: liandyao
date: @date

"""
# 抖音需要标题

tags=["#跟我学英语",
    "#快乐学英语",
    "#寒假学英语",
    "#英语小达人",
    "#趣味学英语",
    "#每天一句英语",
    "#玩着学英语",
    "#英语启蒙小课堂",
    "#英语开口说",
    "#英语单词魔法书",
    "#亲子学英语",
    "#少儿英语我最棒",
    "#轻松早教学英语",
    "#宝宝爱英语",
    "#英语儿歌欢乐颂",
    "#玩中记单词",
    "#学英语从0开始",
    "#孩子的英语秘密",
    "#暑假学英语",
    "#英语奇妙冒险",
    "#掌握英语没烦恼",
    "#英语故事时间",
    "#小小英语天地",
    "#一起玩转英语",
    "#英语小剧场",
    "#英语启蒙魔法班",
    "#英语有趣学起来",
    "#幼儿英语早教启蒙",
    "#每天和宝宝学英语",
    "#少儿英语酷课堂",
    "#英语学习打卡中",
    "#家庭趣味学英语",
    "#英语新手村",
    "#少儿英语成长记",
    "#孩子的英语启蒙日记",
    "#英语词汇王",
    "#英语小冒险家",
    "#边玩边学英语",
    "#儿童英语趣味营",
    "#英语互动课堂",
    "#学英语从玩拼图开始",
    "#英语阅读童趣时光",
    "#一日一句英语启蒙",
    "#学会英语好轻松",
    "#让孩子爱上英语",
    "#英语快乐成长记",
    "#少儿双语小百科",
    "#英语语感培养屋",
    "#英语学习小能手"]

class AutoRelease:
    def __init__(self, titles,  descris,tags=tags):
        # 初始化参数并将其存储为实例变量
        self.titles = titles  # 文字标题列表
        self.descris = descris  # 描述
        self.tags = tags  # 标签

    # 快手发布
    '''
    video_path 表示视频的路径
    title 表示需要写在封面的标题
    account_en 是账号的英文名称或者数字,不要使用中文
    '''
    def auto_release_kuaishou(self,video_path,title,account_en):
        # 创建 ChromeOptions，并指定 chrome.exe 的路径
        # 获取当前工作目录
        base_dir = os.getcwd()

        # 指定一个新的用户数据目录
        new_user_data_directory = os.path.join(base_dir, f"User_Data_ks_{account_en}")
        if not os.path.exists(new_user_data_directory):
            os.makedirs(new_user_data_directory)

        # 创建 ChromeOptions
        options = webdriver.ChromeOptions()
        options.add_argument(f"user-data-dir={new_user_data_directory}")  # 使用新的用户数据目录
        options.add_argument("profile-directory=Default")
        options.add_argument("--start-maximized")  # 最大化窗口

        # 启动 Chrome
        driver = webdriver.Chrome(options=options)

        try:
            driver.get("https://cp.kuaishou.com/article/publish/video")
        except Exception as e:
            print(f"Failed to load page: {e}")

        time.sleep(10)
        print('开始上传视频.')
        # 视频上传
        file_input = WebDriverWait(driver, 600).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='file']")))

        file_input.send_keys(video_path)
        print('上传完成')

        time.sleep(3)
        try:
            # 等待第三个按钮出现  -- 第三个是合集
            button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable(
                    (By.XPATH,
                     "(//div[contains(@class, 'ant-select ant-select-single ant-select-allow-clear ant-select-show-arrow')])[4]")
                )
            )

            print("找到按钮，准备点击。")

            # 点击按钮
            button.click()
            print("合集按钮已被点击。")

            time.sleep(3)
            # 等待并找到第一个具有 ant-select-item-option 类的 div 元素
            first_item = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "div.ant-select-item-option"))
            )

            # 点击该元素
            first_item.click()
            print("已点击活跃选项。")
        except Exception as e:
            print(f"快手发布Error: {e}")

        random_title=''
        # 随机选择一个标题
        if len(self.titles) > 0:
            random_title = random.choice(self.titles)
        print(random_title)
        time.sleep(3)
        descri = random.choice(self.descris)
        # 填写描述
        title_input = WebDriverWait(driver, 150).until(
            EC.element_to_be_clickable((By.ID, "work-description-edit")))
        title_input.send_keys(f"{title} {random_title} {descri} ")
        # 每次加三个标签
        title_input.send_keys("#快成长计划 ")
        title_input.send_keys(f"{random.choice(self.tags).replace('抖音','快手')} ")
        time.sleep(2)
        title_input.send_keys(f"{random.choice(self.tags).replace('抖音','快手')} ")
        time.sleep(1)
        title_input.send_keys(f"{random.choice(self.tags).replace('抖音','快手')} ")


        # 等待直到特定类名的元素出现-当有预览按钮时,说明上传成功
        preview_header = WebDriverWait(driver, 240).until(
            EC.presence_of_element_located((By.CLASS_NAME, "_preview-header_1ahzu_92"))
        )
        print("找到元素，继续执行下一步。")

        # 发布
        time.sleep(3)
        # 等待并找到具有特定类名并包含"发布"文本的 div 元素
        publish_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH,
                                        "//div[contains(@class, '_button_si04s_1') and contains(@class, '_button-primary_si04s_60')]//div[text()='发布']"))
        )

        # 点击该元素
        publish_button.click()

        print("已点击发布按钮。")

        # 等待 10 秒
        time.sleep(10)


        driver.quit()  # 确保在完成后关闭浏览器


    def auto_release_douyin(self,video_path,title,account_en):

        # 创建 ChromeOptions，并指定 chrome.exe 的路径
        # 获取当前工作目录
        base_dir = os.getcwd()

        # 指定一个新的用户数据目录
        new_user_data_directory = os.path.join(base_dir, f"User_Data_dy_{account_en}")
        if not os.path.exists(new_user_data_directory):
            os.makedirs(new_user_data_directory)

        # 创建 ChromeOptions
        options = webdriver.ChromeOptions()
        options.add_argument(f"user-data-dir={new_user_data_directory}")  # 使用新的用户数据目录
        options.add_argument("profile-directory=Default")
        options.add_argument("--start-maximized")  # 最大化窗口

        # 启动 Chrome
        driver = webdriver.Chrome(options=options)

        '''
             作用：发布抖音视频
            '''

        # 进入创作者页面，并上传视频
        driver.get("https://creator.douyin.com/creator-micro/content/upload")
        time.sleep(30)
        # 视频上传
        file_input = WebDriverWait(driver, 600).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='file']")))

        file_input.send_keys(video_path)
        print('上传完成')

        time.sleep(10)

        # 等待输入框加载并获取元素
        input_element = WebDriverWait(driver, 600).until(
            EC.visibility_of_element_located((By.XPATH, "//input[@class='semi-input semi-input-default' and @type='text']"))
        )


        # 随机选择一个标题
        random_title = random.choice(self.titles)
        print(random_title)

        input_element.send_keys(f"{title} ")  # 替换为你要设置的文本
        input_element.send_keys(f'{random_title}')
        time.sleep(2)
        # 等待加载 input 元素  标题
        input_element2 = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.CLASS_NAME, 'editor-kit-container'))
        )
        time.sleep(2)
        # 随机选择一个标题
        random_desc = random.choice(self.descris)
        print(random_desc)


        # 设置文本
        input_element2.send_keys(f"{random_desc} ")  # 替换为你要设置的文本
        input_element2.send_keys(f"{random.choice(self.tags)} ")
        input_element2.send_keys(f"{random.choice(self.tags)} ")
        input_element2.send_keys(f"{random.choice(self.tags)} ")

        time.sleep(2)

        # 加入活动标识
        try:
            # 等待目标类似结构的 div 元素及其包含“动画”文本的下级 div 加载
            target_element = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located(
                    (
                        By.XPATH,
                        "//div[contains(@class, 'container-BPqaWp activity-right-N1pBMo')]//div[descendant::text()[contains(., '动画')]]"
                    )
                )
            )

            # 点击该元素
            target_element.click()
            time.sleep(2)
        except Exception as e:
            print(f"没有相关活动：{e}")

        try:
            # 加入合集
            # 等待并点击第一个下拉框的 div semi-select select-collection-VQbX7A semi-select-single
            select_div = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable(
                    (By.CLASS_NAME, "semi-select.select-collection-VQbX7A")
                )
            )
            select_div.click()  # 点击下拉选择框
            time.sleep(1)
            # 第二个合集,索引从1开始
            index = 1
            # 等待下拉选项出现，并找到第一个选项并点击
            first_option = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable(
                    (By.XPATH, "(//div[contains(@class, 'semi-select-option collection-option')])[" + str(index) + "]")
                )
            )

            first_option.click()
            print('成功点击合集')


        except Exception as e:
            print(f"未找到目标元素，错误信息：{e}")

        time.sleep(20)
        # 等待并检查是否存在包含"重新上传"文本的 div
        upload_div = WebDriverWait(driver, 180).until(
            EC.visibility_of_element_located(
                (By.XPATH, "//div[contains(text(), '重新上传')]")  # 使用 XPath 来查找包含文本的 div
            )
        )

        # 如果找到了 upload_div，则输出成功信息
        print("上传成功！可以点击发布按钮。")

        # 滚动到底部
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(4)  # 等待滚动完成


        publish_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable(
                (By.XPATH,
                 "//button[contains(@class, 'primary-cECiOJ')]")
            )
        )



        # 点击发布按钮
        publish_button.click()

        print("已点击发布按钮。")

        # 等待 10 秒
        time.sleep(10)

        driver.quit()  # 确保在完成后关闭浏览器

def deletFile(video_path_new):
    if os.path.exists(video_path_new):
        os.remove(video_path_new)
        print(f"已删除文件: {video_path_new}")
    else:
        print(f"文件 {video_path_new} 不存在，无法删除。")

#auto_release_kuaishou('J:\\202410视频剪辑\\猫和老鼠\\python\\38_20241223_095030_1.mp4','秃鹰耍猫')
#auto_release_douyin_qinggan('J:\\202410视频剪辑\\猫和老鼠\\python\\input.mp4','猫和老鼠。')
if __name__ == '__main__':

    titles = [
        "快乐英语，轻松学习！",
        "坚持学习，成就未来！",
        "英语学习，乐趣无穷！",
        "和我一起，快乐学英语！",
        "小小英语家，梦想启航！",
        "每天进步，英语不怕！",
        "英语学习，快乐每一天！",
        "一起玩英语，轻松乐学！",
        "探索英语世界，发现新乐趣！",
        "坚持就是胜利，英语更精彩！",
        "学英语，开启新冒险！",
        "小小英语，梦想大大！",
        "开心学习，快乐成长！",
        "英语启蒙，快乐起航！",
        "向未来出发，英语与你同行！",
        "勇敢说英语，赢得自信！",
        "一起唱歌学英语，快乐无比！",
        "小小口语家，英语我来拿！",
        "用英语讲故事，分享快乐时光！",
        "快乐英语，天天向上！",
        "从小爱上英语，未来无限可能！",
        "语言之旅，从英语开始！",
        "英语是朋友，学习更轻松！",
        "轻松学英语，快乐每一秒！",
        "坚持每一天，英语自然来！",
        "小小挑战，英语不怕！",
        "快乐学习英语，梦想在前方！",
        "英语启航，探索更广阔的世界！",
        "我的英语，带我去旅行！",
        "每天一小步，英语大进步！",
        "让英语伴我成长，快乐无限！",
        "快乐英语，轻松学习！",
        "坚持学习，成就未来！",
        "英语学习，乐趣无穷！",
        "和我一起，快乐学英语！",
        "小小英语家，梦想启航！",
        "每天进步，英语不怕！",
        "英语学习，快乐每一天！",
        "一起玩英语，轻松乐学！",
        "探索英语世界，发现新乐趣！",
        "坚持就是胜利，英语更精彩！",
        "学英语，开启新冒险！",
        "小小英语，梦想大大！",
        "开心学习，快乐成长！",
        "英语启蒙，快乐起航！",
        "向未来出发，英语与你同行！",
        "勇敢说英语，赢得自信！",
        "一起唱歌学英语，快乐无比！",
        "小小口语家，英语我来拿！",
        "用英语讲故事，分享快乐时光！",
        "快乐英语，天天向上！",
        "从小爱上英语，未来无限可能！",
        "语言之旅，从英语开始！",
        "英语是朋友，学习更轻松！",
        "轻松学英语，快乐每一秒！",
        "坚持每一天，英语自然来！",
        "小小挑战，英语不怕！",
        "快乐学习英语，梦想在前方！",
        "英语启航，探索更广阔的世界！",
        "我的英语，带我去旅行！",
        "每天一小步，英语大进步！",
        "让英语伴我成长，快乐无限！",
        "英语学习，快乐不止步！",
        "小小英语梦想，大大精彩未来！",
        "与英语相伴，快乐成长每一天！",
        "勇敢表达，英语无障碍！",
        "知识的钥匙，英语开启未来！",
        "一同探索英语，让学习更有趣！",
        "英语学习，让我与世界对话！",
        "学英语，开创无限可能！",
        "努力学习，收获美好英语！",
        "英语如歌，乐在其中！",
        "走进英语的世界，享受每一刻！",
        "轻松乐学，英语让你行！",
        "每天一点英语，快乐新发现！",
        "用英语讲述我的故事！"
    ]

    descris = [
        "Believe you can and you're halfway there. - 相信自己能做到，你就已经成功一半了。",
        "The future belongs to those who believe in the beauty of their dreams. - 未来属于那些相信梦想之美的人。",
        "You only live once, but if you do it right, once is enough. - 你只活一次，但如果你活得精彩，一次就足够了。",
        "Don't be afraid to give up the good to go for the great. - 不要害怕放弃好的，去追求更伟大的。",
        "It does not matter how slowly you go as long as you do not stop. - 只要你不停止，慢慢前进也没关系。",
        "Your time is limited, don't waste it living someone else's life. - 你的时间有限，不要浪费在过别人的生活上。",
        "Dream big and dare to fail. - 大胆梦想，勇敢面对失败。",
        "You are braver than you believe, stronger than you seem, and smarter than you think. - 你比自己想象的更勇敢、更强大、更聪明。",
        "The only limit to our realization of tomorrow will be our doubts of today. - 我们对明天的实现唯一的限制是今天的怀疑。",
        "Be yourself; everyone else is already taken. - 做你自己；其他人都已经被占用了。",
        "Life is what happens when you're busy making other plans. - 生活是在你忙着制定其他计划时发生的。",
        "Don't count the days, make the days count. - 不要数日子，要让日子有意义。",
        "In the end, we only regret the chances we didn't take. - 最终，我们只会后悔没有抓住的机会。",
        "Your life is your story, and the adventure ahead of you is the journey to fulfill your own purpose and potential. - 你的人生是你的故事，前方的冒险是实现自己目标和潜力的旅程。",
        "Don't let yesterday take up too much of today. - 不要让昨天占据你今天太多的时间。",
        "What lies behind us and what lies before us are tiny matters compared to what lies within us. - 我们身后和面前的事情相比，内心的力量才是最重要的。",
        "It's not whether you get knocked down, it's whether you get back up. - 重要的不是你是否跌倒，而是你是否能重新站起来。",
        "You have brains in your head. You have feet in your shoes. You can steer yourself any direction you choose. - 你有智慧，你有双脚，你可以朝任何你选择的方向前进。",
        "Believe in yourself and all that you are. - 相信自己和你的一切。",
        "You are never too young to dream big. - 你永远不会太小，无法有大梦想。",
        "The more that you read, the more things you will know. - 你读得越多，知道的事情就越多。",  # 出自 Dr. Seuss
        "It's always fun to learn something new! - 学习新知识总是很有趣！",
        "Mistakes are proof that you are trying. - 错误是你努力的证明。",
        "You have the power to make your dreams come true. - 你有能力实现你的梦想。",
        "Every day is a new beginning. Take a deep breath and start again. - 每一天都是新的开始。深呼吸，重新开始。",
        "Be a rainbow in someone else's cloud. - 成为别人生活中的彩虹。",
        "Have courage and be kind. - 要有勇气，并且要善良。",
        "Today is full of possibilities! - 今天充满了无限可能！",
        "You can do anything you set your mind to. - 只要你想做，什么都能做到。",
        "Dream big, little one! - 大胆梦想，小朋友！",
        "Believe you can and you will. - 相信自己能做到，你就会做到。",
        "Keep trying, never give up! - 不断尝试，绝不放弃！",
        "It’s okay to be different. - 不同是好的。",
        "You are amazing just the way you are. - 你就是这样的你，已经很棒了！",
        "The more you practice, the better you get! - 你练习得越多，越会变得更好！",
        "Smile and the world smiles with you. - 微笑吧，世界会与你同欢！"
    ]
    # 初始化自动发布对象
    auto = AutoRelease(titles=titles,descris=descris)

    titles =[
        # {"num": 1, "title": "西游记1"},
        # {"num": 2, "title": "西游记2"},
        # {"num": 3, "title": "西游记3"},
        # {"num": 4, "title": "西游记4"},
        # {"num": 5, "title": "西游记5"},
        # {"num": 6, "title": "西游记6"},
        # {"num": 7, "title": "西游记7"},
        # {"num": 8, "title": "西游记8"},
        # {"num": 9, "title": "西游记9"},
        # {"num": 10, "title": "西游记10"},
        # {"num": 11, "title": "西游记11"},
        # {"num": 12, "title": "西游记12"},
        # {"num": 13, "title": "西游记13"},
        # {"num": 14, "title": "西游记14"},
        # {"num": 15, "title": "西游记15"},
        # {"num": 16, "title": "西游记16"},
        # {"num": 17, "title": "西游记17"},
        # {"num": 18, "title": "西游记18"},
        # {"num": 19, "title": "西游记19"},

        # {"num": 36, "title": "西游记36"},
        # {"num": 37, "title": "西游记37"},
        # {"num": 38, "title": "西游记38"},
        # {"num": 39, "title": "西游记39"},
        # {"num": 40, "title": "西游记40"},
        # {"num": 41, "title": "西游记41"},
        # {"num": 42, "title": "西游记42"},
        # {"num": 43, "title": "西游记43"},


        # {"num": 90, "title": "西游记90"},
        {"num": 91, "title": "西游记91"},
        {"num": 92, "title": "西游记92"},
        {"num": 93, "title": "西游记93"},
        {"num": 94, "title": "西游记94"},
        {"num": 95, "title": "西游记95"},
        {"num": 96, "title": "西游记96"},
        {"num": 97, "title": "西游记97"},
        {"num": 98, "title": "西游记98"},
        {"num": 99, "title": "西游记99"},
        {"num": 100, "title": "西游记100"},
        {"num": 101, "title": "西游记101"},
        {"num": 102, "title": "西游记102"},
        {"num": 103, "title": "西游记103"},
        {"num": 104, "title": "西游记104"},
        {"num": 105, "title": "西游记105"},
        {"num": 106, "title": "西游记106"},
        {"num": 107, "title": "西游记107"},
        {"num": 108, "title": "西游记108"},





    ]

    base_path = 'G:\\BaiduNetdiskDownload\\少儿英语动画全集分级\\6、西游记动画片 英文版108集【中英文字幕】\\1.中英双字幕版108集视频\\'
    for i in titles:
        print(i)
        # 开始自动发布
        video_path = f'{base_path}\\{i["num"]}.mp4'
        title = i["title"]
        video_path_new = f'{base_path}\\{i["num"]}_1.mp4'
        add_video_cover.clip_video(video_path, video_path_new, '00:00:06')
        #mask_path = add_video_cover.add_mask(video_path_new)

        # 加入封面
        new_path = add_video_cover.start(video_path_new, title)

        time.sleep(10) # 休息10秒
        auto.auto_release_douyin(video_path=new_path, title=title, account_en='mengbao')
        #auto.auto_release_douyin(video_path=new_path, title=title, account_en='baozi') 账号已改名AI数据视界
        auto.auto_release_kuaishou(video_path=new_path, title=title, account_en='yingyu1')
        auto.auto_release_kuaishou(video_path=new_path, title=title, account_en='bannichengzhang')
        # 删除水印输出文件
        #deletFile(video_path_new)
        deletFile(video_path_new)

